﻿using SortingNetworkSimulator.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SortingNetworkSimulator.Creators
{
    class InsertSortNetwork
    {
        private Network network { get; set; }

        public InsertSortNetwork(int inputsCount)
        {
            this.network = new Network(inputsCount);
        }

        public InsertSortNetwork(Network network)
        {
            this.network = network;
        }

        public Network Transform()
        {
            List<ComparatorData> comparators = new List<ComparatorData>();
            ComparatorData cd;

            int layersTemp;

            if (network.InputsCount == 2)
            {
                layersTemp = 1;
            }
            else if (network.InputsCount == 3)
            {
                layersTemp = 2;
            }
            else
            {
                layersTemp = network.InputsCount + (network.InputsCount - 3);
            }


            for (int i = 0; i < network.InputsCount; i++)
            {
                for (int j = i; j <= layersTemp-i; j += 2)
                {
                    cd.Layer = j;
                    cd.WireOneIndex = i;
                    cd.WireTwoIndex = i + 1;
                    comparators.Add(cd);
                }
            }

            var sortedList = comparators.OrderBy(p => p.Layer);

            foreach (ComparatorData comparatorData in sortedList)
            {
                network.AddComparator(comparatorData.WireOneIndex, comparatorData.WireTwoIndex, comparatorData.Layer);
            }

            return network;
        }

    }

    struct ComparatorData
    {
        public int WireOneIndex;
        public int WireTwoIndex;
        public int Layer;
    }
}
